/*
 *  This file is part of AtlasMapper server and clients.
 *
 *  Copyright (C) 2012 Australian Institute of Marine Science
 *
 *  Contact: Gael Lafond <g.lafond@aims.org.au>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package au.gov.aims.metadatagenerator.importer;

import au.gov.aims.metadatagenerator.entity.Address;
import au.gov.aims.metadatagenerator.entity.Contact;
import au.gov.aims.metadatagenerator.entity.ContactRoleCode;
import au.gov.aims.metadatagenerator.entity.NERPProjectColumn;
import au.gov.aims.metadatagenerator.entity.Project;
import org.apache.commons.csv.CSVParser;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NERPProjectImporter extends Importer<Project> {
	private static final Logger LOGGER = Logger.getLogger(NERPProjectImporter.class.getName());

	@Override
	public List<Project> importFile(File file) throws Exception {
		List<Project> projects = new ArrayList<Project>();
		Reader reader = null;

		try {
			// See: http://lucene.apache.org/solr/4_5_0/solr-core/index.html
			// What are those??
			//     * http://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVParser.html
			//     * http://commons.apache.org/proper/commons-csv/
			reader = new FileReader(file);

			Project project; File outputFile;

			CSVParser parser = new CSVParser(reader);

			// 1 column = 1 project.
			// If it was 1 project per line, I could use getLine() and process the file sequentially (more memory efficient).
			String[][] values = parser.getAllValues();

			// The 2 first column are metadata.
			int nbProjects = values[0].length - 2;

			LOGGER.log(Level.INFO, "The file contains {0} projects", nbProjects);
			for (int i=0; i<nbProjects; i++) {
				int col = i+2; // Skip the first 2 columns

				project = new Project();

				project.setProjectNumber(NERPProjectColumn.PROJECT_NO.get(values, col));
				project.setURL(NERPProjectColumn.URL.get(values, col));

				project.setCompleted(Boolean.parseBoolean(values[NERPProjectColumn.COMPLETED.getColumnNumber()-1][col]));

				project.setUUID(NERPProjectColumn.UUID.get(values, col));

				project.setTitle(NERPProjectColumn.TITLE.get(values, col));
				project.setAbstract(NERPProjectColumn.ABSTRACT.get(values, col));
				project.setPurpose(NERPProjectColumn.PURPOSE.get(values, col));

				project.setStart(NERPProjectColumn.START.get(values, col));
				project.setEnd(NERPProjectColumn.END.get(values, col));

				project.setStudyLocations(NERPProjectColumn.STUDY_LOCATIONS.get(values, col));
				project.setSuggestedSubmissionMethod(NERPProjectColumn.SUGGESTED_SUBMISSION_METHOD.get(values, col));


				String principalInvestigatorName = NERPProjectColumn.PRINCIPAL_INVESTIGATOR_NAME.get(values, col);
				if (principalInvestigatorName != null && !principalInvestigatorName.trim().isEmpty()) {
					Contact principalInvestigator = new Contact();
					principalInvestigator.setName(principalInvestigatorName);
					principalInvestigator.setOrganisation(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_ORGANISATION.get(values, col));
					principalInvestigator.setPosition(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_POSITION.get(values, col));
					principalInvestigator.setRole(ContactRoleCode.PRINCIPAL_INVESTIGATOR);
					principalInvestigator.setPhoneNumber(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_PHONE_NUMBER.get(values, col));

					Address principalInvestigatorAddress = new Address();
					principalInvestigatorAddress.setAddress(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_ADDRESS.get(values, col));
					principalInvestigatorAddress.setCity(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_CITY.get(values, col));
					principalInvestigatorAddress.setState(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_STATE.get(values, col));
					principalInvestigatorAddress.setPostalCode(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_POSTALCODE.get(values, col));
					principalInvestigatorAddress.setCountry("Australia");
					principalInvestigatorAddress.setEmail(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_EMAIL.get(values, col));
					principalInvestigator.setAddress(principalInvestigatorAddress);

					principalInvestigator.setOnlineProfile(NERPProjectColumn.PRINCIPAL_INVESTIGATOR_ONLINE_PROFILE.get(values, col));

					project.addPointOfContact(principalInvestigator);
				}

				String coInvestigatorName = NERPProjectColumn.CO_INVESTIGATOR_NAME.get(values, col);
				if (coInvestigatorName != null && !coInvestigatorName.trim().isEmpty()) {
					Contact coInvestigator = new Contact();
					coInvestigator.setName(coInvestigatorName);
					coInvestigator.setOrganisation(NERPProjectColumn.CO_INVESTIGATOR_ORGANISATION.get(values, col));
					coInvestigator.setPosition(NERPProjectColumn.CO_INVESTIGATOR_POSITION.get(values, col));
					coInvestigator.setRole(ContactRoleCode.CO_INVESTIGATOR);
					coInvestigator.setPhoneNumber(NERPProjectColumn.CO_INVESTIGATOR_PHONE_NUMBER.get(values, col));

					Address coInvestigatorAddress = new Address();
					coInvestigatorAddress.setAddress(NERPProjectColumn.CO_INVESTIGATOR_ADDRESS.get(values, col));
					coInvestigatorAddress.setCity(NERPProjectColumn.CO_INVESTIGATOR_CITY.get(values, col));
					coInvestigatorAddress.setState(NERPProjectColumn.CO_INVESTIGATOR_STATE.get(values, col));
					coInvestigatorAddress.setPostalCode(NERPProjectColumn.CO_INVESTIGATOR_POSTALCODE.get(values, col));
					coInvestigatorAddress.setCountry("Australia");
					coInvestigatorAddress.setEmail(NERPProjectColumn.CO_INVESTIGATOR_EMAIL.get(values, col));
					coInvestigator.setAddress(coInvestigatorAddress);

					coInvestigator.setOnlineProfile(NERPProjectColumn.CO_INVESTIGATOR_ONLINE_PROFILE.get(values, col));

					project.addPointOfContact(coInvestigator);
				}


				project.setTopicCategoryCode(NERPProjectColumn.CATEGORY.get(values, col));
				project.setCredit(NERPProjectColumn.CREDIT.get(values, col));

				// TODO Create a WKT exporter that export the WKT String to a MEST Point, Line or Polygon
				String wktStr = NERPProjectColumn.WKT.get(values, col);
				if (wktStr != null && !wktStr.trim().isEmpty()) {
					String[] wktArr = wktStr.trim().split(";");
					for (String wkt : wktArr) {
						if (wkt != null && !wkt.trim().isEmpty()) {
							project.addWKT(wkt.trim().toUpperCase());
						}
					}
				}

				project.setWMSLayerPoints(NERPProjectColumn.WMS_LAYER_POINTS.get(values, col));
				project.setWMSLayerLines(NERPProjectColumn.WMS_LAYER_LINES.get(values, col));
				project.setWMSLayerPolygons(NERPProjectColumn.WMS_LAYER_POLYGONS.get(values, col));

				project.setPDFMapURL(NERPProjectColumn.PDF_MAP_URL.get(values, col));

				project.setParentUUID(NERPProjectColumn.PARENT_UUID.get(values, col));

				projects.add(project);
			}
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch(Exception ex) {
					LOGGER.log(Level.WARNING, "Can not close the CSV file reader", ex);
				}
			}
		}

		return projects;
	}
}
